package com.school.edupoint.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.school.edupoint.properties.OssProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


@Component
@Slf4j
public class OssTemplate {

    private final OssProperties ossProperties;
    private  OSS ossClient; // 单例复用
    private final Random random = new Random(); // 用于生成随机数

    @PostConstruct
    public void init() {
        this.ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKey(),
                ossProperties.getSecret()
        );
        log.info("OSSClient 初始化成功");
    }

    @PreDestroy
    public void destroy() {
        if (ossClient != null) {
            ossClient.shutdown();
            log.info("OSSClient 已关闭");
        }
    }


    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;

    }

    //上传
    public String upload(String originalName, InputStream inputStream) {
        int dotIndex = originalName.lastIndexOf('.');
        String baseName = (dotIndex > 0) ? originalName.substring(0, dotIndex) : originalName;
        String extension = (dotIndex > 0) ? originalName.substring(dotIndex) : "";

        try {
            String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            long timestamp = System.currentTimeMillis();
            int randomNum = random.nextInt(100000);
            String randomStr = String.format("%05d", randomNum);

            String objectName = dateDir + "/" + baseName + "_" + timestamp + randomStr + extension;

            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossProperties.getBucketName(),
                    objectName,
                    inputStream
            );

            ossClient.putObject(putObjectRequest);

            return ossProperties.getUrl() + "/" + objectName;
        } catch (Exception e) {
            log.error("OSS上传失败", e);
            throw new RuntimeException("OSS上传失败", e);
        }
    }

    /**
     * 从 OSS 的访问 URL 提取 objectName
     *
     * @param fileUrl OSS 文件访问地址
     * @return objectName 路径
     */
    private String extractObjectNameFromUrl(String fileUrl) {
        if (fileUrl == null || !fileUrl.startsWith(ossProperties.getUrl())) {
            return null;
        }

        // 去除域名部分，保留路径和文件名
        return fileUrl.substring(ossProperties.getUrl().length() + 1); // +1 是去掉斜杠
    }

    /**
     * 根据 OSS 文件的完整访问 URL 删除文件
     *
     * @param fileUrl OSS 文件的完整 URL 地址
     * @return 是否删除成功
     * 异步删除文件
     */
    @Async
    public void asyncDeleteByUrl(String fileUrl) {
        try {
            boolean deleted = deleteByUrl(fileUrl);
            if (deleted) {
                log.info("异步删除 OSS 文件成功: {}", fileUrl);
            } else {
                log.warn("异步删除 OSS 文件失败或不存在: {}", fileUrl);
            }
        } catch (Exception e) {
            log.error("异步删除 OSS 文件异常: {}", fileUrl, e);
        }
    }


    public boolean deleteByUrl(String fileUrl) {
        String objectName = extractObjectNameFromUrl(fileUrl);
        if (objectName == null || objectName.isEmpty()) {
            return false; // URL 不合法或不匹配域名
        }

        try {
            delete(objectName);
            return true;
        } catch (Exception e) {
            // 可选：记录日志
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据 OSS 文件路径删除文件
     *
     * @param objectName 文件在 OSS 中的路径，例如："2025/06/10/OIP-C_174956430750602884.jpg"
     */
    public void delete(String objectName) {
        OSS ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKey(),
                ossProperties.getSecret()
        );
        try {
            ossClient.deleteObject(ossProperties.getBucketName(), objectName);
        } finally {
            ossClient.shutdown();
        }
    }


}